package com.atguigu.jxc.advice;

import com.atguigu.jxc.annotation.LogToDb;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;

@Aspect
@Component
@Slf4j
public class LogAdvice {
    @Autowired
    private LogService logService;

    @Autowired
    private UserDao userDao;

    @AfterReturning("@annotation(com.atguigu.jxc.annotation.LogToDb)")
    public void log(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        LogToDb logToDb = method.getAnnotation(LogToDb.class);
        Log log = new Log();
        log.setLogDate(new Date());
        User userByName = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        log.setUserId(userByName.getUserId());
        log.setLogType(StringUtil.isEmpty(logToDb.logType()) ? method.getName() : logToDb.logType());
        log.setContent(StringUtil.isEmpty(logToDb.content()) ? Arrays.toString(method.getParameters()) : logToDb.content());
//        logService.save(log);
        System.out.println(log);
        LogAdvice.log.info("{}-{}({})", log.getUserId(), log.getLogType(), log.getContent());
    }

    @AfterThrowing(value = "@annotation(com.atguigu.jxc.annotation.LogToDb)")
    public void logErr(JoinPoint joinPoint) {
        System.out.println(joinPoint.getKind());
        System.out.println(Arrays.toString(joinPoint.getArgs()));
    }
}
